package com.html2rss.core;

import org.apache.commons.httpclient.URIException;

import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;

import com.sun.tools.javac.util.Pair;

/**
 * User: VSlaykovskiy
 * Date: 10.04.2007
 * Time: 16:52:08
 */
public class HttpURL extends org.apache.commons.httpclient.HttpURL {
    private List<Pair<String, String>> queryParams;


    public HttpURL(String destPath) throws URIException {
        super(destPath);
        initQueryParams();
    }





    public void setQuery(String string, String string1) throws URIException, NullPointerException {
        super.setQuery(string, string1);
        initQueryParams();
    }

    public void setQuery(String []a, String []b) throws URIException, NullPointerException {
        super.setQuery(a,b);
        initQueryParams();
    }


    public void setQuery(String string) throws URIException {
        super.setQuery(string);
        initQueryParams();
    }

    private void initQueryParams() throws URIException {
        queryParams = new ArrayList<Pair<String, String>>();
        String query = getQuery();
        if (query == null) return;
        String[] params = query.split("&");
        for (String param : params) {
            if (param != null && param.length() > 0) {
                String[] pair = param.split("=");
                if (pair.length  == 2) {
                    queryParams.add(new Pair<String, String>(pair[0], pair[1]));
                }
            }
        }
    }

    public void setPath(String string) throws URIException {
        super.setPath(string);
        initQueryParams();
    }

    public void addQueryParameter(String param, String value) throws URIException {
        setQuery( (getQuery()==null?"":getQuery()+"&") +param+"="+value);
    }

    public void addAllQueryParameters(Map <String, String[]> params) throws URIException {
        String result = "";
        for (String param:params.keySet()) {
            for (String value: params.get(param)) {
                result+=param+"="+value+"&";
            }
        }
        setQuery(getQuery()==null?"":getQuery()+"&"+result);
    }

    public String getHostPort( ) throws URIException {
        return  getScheme()+"://"+getHost()+":"+getPort();
    }

    public String getHostPortHierPath( ) throws URIException {
        return getHostPort()+getCurrentHierPath();
    }

    public List<Pair<String, String>> getQueryParams() {
        return queryParams;
    }

    public void setQueryParams(List<Pair<String, String>> queryParams) {
        this.queryParams = queryParams;
    }
}
